package hd.util.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * 通用的适配器
 * <p/>
 * Created by Haidy on 14/11/9.
 */
public abstract class UniAdapter<T, K> extends BaseAdapter {

    private final Context context;
    private List<T> dataList = new ArrayList<>();

    public UniAdapter(Context context) {
        this.context = context;
    }

    @Override
    public int getCount() {
        return dataList.size();
    }

    public void setData(@NonNull List<T> data) {
        dataList.clear();
        addAllData(data);
    }

    public void addData(T t) {
        dataList.add(t);
        notifyDataSetChanged();
    }

    public void addData(T t, int index) {
        dataList.add(index, t);
        notifyDataSetChanged();
    }

    public void addAllData(@NonNull List<T> dataList) {
        this.dataList.addAll(dataList);
        notifyDataSetChanged();
    }

    /**
     * 移除一项
     *
     * @param index 位置
     */
    public void remove(int index) {
        if (dataList.size() >= index + 1)
            dataList.remove(index);
        notifyDataSetChanged();
    }

    public void clear() {
        dataList.clear();
        notifyDataSetChanged();
    }

    @Override
    public T getItem(int position) {
        return dataList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public abstract int getContentView();

    public abstract BaseViewHolder<T, K> getHolder();

    public abstract K initViewHolder(View convertView);

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        BaseViewHolder<T, K> holder;
        if (convertView == null) {
            convertView = View.inflate(context, getContentView(), null);
            K k = initViewHolder(convertView);
            holder = getHolder();
            holder.setHolder(k);
            convertView.setTag(holder);
        } else {
            holder = (BaseViewHolder<T, K>) convertView.getTag();
        }
        holder.loadData(holder.getHolder(), getItem(position), position);
        return convertView;
    }

}
